
gilistsArray = new Array();// Array of Group Indicators
grphArr = new Array();// Array of Graph values
grphTable = new Array();//Look up table for graph type. Index of grphTable is nsync with grphArr.
grphCur = new Array();// Current graph data
loginData = {};
mbfields = new Array(); //multibar fields
axisValues = new Array();
axisName = new Array();
pieTitle = "PieTest";
barTitle = "barTest";
multibarTitle = "mbTest";
xTitle = "Values";
barHeight = 0;
mbLabelVal = new Array();



//Remove empty arrays
function remEmptyArr(array, gilistsArray,emptyArray){
    var cnt = 0;
    var adjustedArray = new Array();
    //Count only indexes with array size > 0
    for (var i=0; i<array.length; i++){
	if (array[i].length != 0) {
	    cnt++;
	    
	}
    }
    // fill up empty array with menu items that actually have graphs.
    var updatedIndex = 1;
    for (var m=0; m<array.length; m++){
	
	if (array[m].length != 0) {
	emptyArray.push(array[m]);
	gilistsArray[m].firstName = updatedIndex;
	adjustedArray.push(gilistsArray[m]);
	updatedIndex++;
	}
    }
    return adjustedArray;
}

/**Ajax Request (Submits the form below through AJAX
*               and then calls the ajax_response function)
*/
function ajax_request() {
    var submitTo = 'https://p2p.b-pack.com/a/endemo/api3/report/groups?oauth_token=1269dbe2f45d3a7aa6b19c212f60954c';
    var data = http2('GET', submitTo); //, document.form1);
    for (var label in data.list) {
        //Create pair javascript object pairs
        var temp1 = { firstName: label, lastName: data.list[label] };
        //Load objects into array (The "data" property of the Sencha's Ext.data.JsonStore object consumes this array )
        gilistsArray.push(temp1);
    }

}

// 2d array first indexed by Group Indicator, then by graph name.
// This 2d array will be consulted to get graph metadata.
gilistArray = new Array(gilistsArray.length);


/** ajax_requestGilist2()
 *  Populates 2d array with metadata of graphable items. 
 *  2d array is oragnized by Group Indicator(REPORTGROUPID) which can be indexed in the first array.
 */
function ajax_requestGilist2() {
    var tmpArray = new Array();
    var submitTo = 'https://p2p.b-pack.com/a/endemo/api3/report/browse/index?oauth_token=1269dbe2f45d3a7aa6b19c212f60954c';
    var data = http2('GET', submitTo); //, document.form1);
    //Populate each index of the array with an empty array to 
    for (i=0; i < gilistsArray.length; i++) {gilistArray[i] = new Array();}
    for (var item in data.list) {
        //Only select graph names with actual graph data
        if ((data.list[item]['RTYPE'] == "10") || (data.list[item]['RTYPE'] == "5") || (data.list[item]['RTYPE'] == "16")) {
	    var metadata = {
			    REPORTGROUPID: data.list[item]['REPORTGROUPID'],
			    RTYPE: data.list[item]['RTYPE'],
			    RRNAME: data.list[item]['RRNAME'],
			    RRLABEL: data.list[item]['RRLABEL'],
			    REQREPORTID: data.list[item]['REQREPORTID'],
			    GRAPHTYPE: data.list[item]['GRAPHTYPE']
			};
	    //Logic to determine which Group Indicator to place graph metadata in.
	    var index = (data.list[item]['REPORTGROUPID']);
	    if (!(index==undefined || metadata==undefined))
		gilistArray[index-1].push(metadata);
	}
    }
    gilistsArray = remEmptyArr(gilistArray, gilistsArray, tmpArray);
    gilistArray = tmpArray;
}

/** getGraph(gType, rid)
 *  Loads the grphArr global 2D variable with the data for the request graph.
 *  DETAILS:
 *  Connects to the server and retrieves the json file.
 *  That json file is then parsed into packages and added to a grphArr
 *  The array is then returned
 *  @param gType String that Specifiies type of graph. This value comes directly from the bpack server
 *  @param rid String of report id. It identifies the graph to be viewed
 */
function getGJson(RType, rid, gLabel) {
    var graph = "";
    var gdata = new Array();
    var i=0;
    var fieldsArr = new Array();
    url = 'https://p2p.b-pack.com/a/endemo/api3/report/' + rid + '?oauth_token=1269dbe2f45d3a7aa6b19c212f60954c'; 
    data = http2('GET',url);
    xTitle = data.props.RRLABEL + " Values";
    // Bar Graph
    if (RType=="16") {
	barHeight = 0;
        for (var label in data.labels){ //data.labels accesses the key of each pair
	    if (!(data.list[0][label]==undefined)){
		barHeight = (data.list[0][label] > barHeight) ? parseFloat(data.list[0][label]) : parseFloat(barHeight);
		var obj = {name: data.labels[label], value: data.list[0][label]};
		gdata[i] = obj;
		i++;
	    }
        }
	barHeight = Math.round(barHeight)/1;
	barHeight = barHeight + 10;
	barTitle = gLabel;
	graph = "barCard";
    }
    // MultiBar graph
    else if (RType=="10" || (RType=="5" && data.props.COLCOUNT > 2)) {
	var bkCount = data.props.BREAKCOUNT;
	var m = 0;
	
	var bd = new Array(); // Helper array to identify the breakdown names
	var bkArr = new Array(); // Indexed by the list's index (via json), has concatenated breakdowns
	var cArr = new Array(); // Indexed by the list's index ()via json)
	// Save BREAKDOWN items into array
	for (var it in data.props.BREAKDOWN) {
	    bd.push(it);
	}
	/**
	 * jo - a json object from the list array
	 * load bkArr with all BREAKDOWN items from all the list objects
	 */
	for (var jo in data.list){
	    //insert into bkArr the value of each json object(jo) indexed by the bd array
	    //bkArr is not a 2d array where cArr is.
	    var i = 0;
	    var tmpName = "";
	 
	    for (i=0; i<bd.length; i++){
	    tmpName += tmpName + " " + data.list[[jo]][bd[i]];
	    }
	    if (jo < data.list.length)
	    bkArr.push(tmpName);
	}
	// Make 2d array
	for (j = 0; j<data.list.length; j++) {
	    cArr = new Array();
	}
	/**
	 * load the cArr with all items in the list array objects.
	 */
	var j = 0;
	mbLabelVal = new Array();
	for (var jo in data.list){ // Get each jo item
	    var i = 1;
	    
	    var tmpArr = new Array();
	    var tmpArr1 = new Array();
	    // Get only the it's that come after the breakdown values
	    for (var it in data.list[jo]){ // Get each jo items item
		if (i > bkCount) {
		    var v = data.list[jo][it];
		    tmpArr.push(v);
		    tmpArr1.push(it);
		}
		i++;
	    }
	    if (j < data.list.length) {
		cArr.push(tmpArr);
		mbLabelVal.push(tmpArr1);
		}
	    j++;
	}
	/**
	 * Create the objects and load them into the gdata array
	 */
	var k = 0;
	
	for (k=0; k < bkArr.length; k++) { // C
	    var n = 0;
	    var str = "";
	    mbfields.push('name'); //multibar fields
	    for (n=1; n < cArr[k].length+1; n++) { // Create our string of C values
		str += '\"' + mbLabelVal[k][n-1] + '\": \"' + cArr[k][n-1] + '\",';
	    }
	    str = str.substring(0,str.length-1);
	    var str = '{\"name\": \"' + bkArr[k] + '\", ' + str + '}';
	    gdata[k] = JSON.parse(str);
	    //['name', 'c1', 'c2', 'c3']
	}
	// Generate the arrays for the fields
	jsonObj = gdata[0];
	var x = 0;
	mbfields = new Array();
	
	for (var key in jsonObj){
	    if (x==0) {
		axisName.push(key);
		mbfields.push(key); 
	    }
	    else {
		axisValues.push(key); //goes in the fields for the multibar field in views.js
		mbfields.push(key); 
	    }
	    x++;
	}
	/*
	for (var label in data.labels){
	    axisValues.push(label);
	}
	*/
	
	multibarTitle = gLabel;
	graph = "multiBarCard";
    }
    // Pie Graph
    else if (RType=="5" && data.props.COLCOUNT == 2){ 
	var arr = new Array();
	var i = 0;
	var j = 0;
	var n,v; // Variables for names and values
	/**
	 * We assume every object within the list array are identical in the number of labels b/c that's
	 * 	how the json is structured
	 * This is just to get the names of every label within a typical list object
	 */
	for (var la in data.list[0])
	    {
		arr[i] = la;
		i++;
	    }
	for (var index in data.list){ //data.labels accesses the key of each pair
	    i = 0;
	    n = (data.list[index][arr[i]]==undefined || data.list[index][arr[i]]==null) ? "N/A" : data.list[index][arr[i]];
	    v = (/*(data.list[index][arr[i++]]==undefined) ||*/ data.list[index][arr[i++]]==null) ? 0 : data.list[index][arr[i++]];
	
	    var tmp = {name: n, value: v};
	    gdata[j] = tmp;
	    j++; 
        }
	pieTitle = gLabel;
	graph = "pieCard";
    }
  
    //if (grphArr.length > 10) grphArr = new Array();
    grphArr.push(gdata);
    //Update look up table. Index of grphTable is nsync with grphArr.
    grphTable.push(RType);
    //Sets current graph information
    grphCur = grphArr[(grphTable.length)-1];
    return graph;
}



//Init: Make AJAX Request
ajax_request();
ajax_requestGilist2();

/**********************gilists***********************************************/
bpack.models = {};//wd.models = {}; //namespace for models & stores
bpack.models.gilists = Ext.regModel('Group Indicators', {
    fields: [
             {name: 'firstName', type: "string"},
             {name: 'lastName', type: "string"}
            ],
    gilistsData: null, //Store object
    gilistsData3: null,
    getGilistsData: function() {
        if (!this.gilistsData) {
                this.gilistsData = new Ext.data.Store({
                model: this,
                data: gilistArray[0],
                proxy: null
            })
        }
        return this.gilistsData;
    },
    changeGilists: function(){
        this.gilistsData = new Ext.data.Store({
            model: this,
            data: gilistsArray
        })
        return this.gilistsData;
    }
});
bpack.models.StoreGilists = new Ext.data.Store({
    model: bpack.models.gilists,
    autoLoad: true,
    data: gilistsArray//Json Array
});
/*************************gilist****************************************************/
bpack.models.gilist = Ext.regModel('Group Indicator Graph List', {
    fields: [
		{name: 'REPORTGROUPID', type: "string"},
		{name: 'RRNAME', type: "string"},
		{name: 'RRLABEL', type: "string"},
		{name: 'REQREPORTID', type: "string"},
		{name: 'GRAPHTYPE', type: "string"}
            ],
    data: null, //Store Object
    getStore: function(selectedIndex) {
                this.data = new Ext.data.Store({
                model: bpack.models.gilist,
                autoload: true,
                data: gilistArray[selectedIndex-1]//gilistsArray
            })
        return this.data;
    }
});
/***************************Pie Graph****************************************************/
window.storePie = new Ext.data.JsonStore({
                    fields: ['name', 'value'],
		    autoLoad: true, 
                    data: grphCur
    });
    var onRefreshTap = function() {
        window.storePie.loadData(grphCur);//generateData(6, 2));
    };
    var onHelpTap = function() {
			new Ext.Panel({
			floating: true,
			modal: true,
			centered: true,
			width: 300,
			height: 250,
			styleHtmlContent: true,
			scroll: 'vertical',
			dockedItems: [{
			    dock: 'top',
			    xtype: 'toolbar',
			    title: 'Pie Chart'
			}],
			stopMaskTapEvent: false,
			fullscreen: false,
				html: "This example's uses many interactions.<br><ul>" +
				     "<li>Dragging the Pie Chart will rotate it.</li>" +
				     "<li>Tapping any slice will bring up an overlay which can then be sized to group and total slices together.</li>" +
				     "<li>Tap and hold will bring up additional information about a slice</li>" +
				     "<li>Double-Tap will reset the chart back to the initial state (after confirmation)</li>"
		    }).show('fade');
    }
/***************************Bar Chart***********************************************/
window.storeBar = new Ext.data.JsonStore({
            fields: ['name', 'value'],
            data: grphCur
        });
        var colors = ['url(#v-1)', 'url(#v-2)', 'url(#v-3)', 'url(#v-4)', 'url(#v-5)'];
        var onRefreshTap = function() {
            window.storeBar.loadData(grphCur);
        };	
        var onHelpTap = function() {
	    new Ext.Panel({
		floating: true,
		modal: true,
		centered: true,
		width: 300,
		height: 250,
		styleHtmlContent: true,
		scroll: 'vertical',
		dockedItems: [{
		    dock: 'top',
		    xtype: 'toolbar',
		    title: 'Column Chart'
		}],
	       stopMaskTapEvent: false,
	       fullscreen: false,
		       html: "This example's uses custom styling to make each data point use a different gradient color.<br>" +
					    "The chart can be zoomed horizontally with a pinch gesture, and the panned by dragging.  For devices which do not support multi-touch, an extra toggle button is made available to switch between pan and zoom.  When zoomed in, arrow indicators will be overlayed on the chart to show that more data is available"
	    }).show('pop');
	}

/***************************MultiBar Chart***********************************************/
window.storeMultiBar = new Ext.data.JsonStore({
            fields: mbfields,
	    data: grphCur
        });

        var onRefreshTap = function() {
            //window.storeMultiBar.loadData(grphCur);
        };
        var onHelpTap = function() {
			new Ext.Panel({
 		          floating: true,
		           modal: true,
		           centered: true,
		           width: 300,
		           height: 250,
		           styleHtmlContent: true,
		           scroll: 'vertical',
		           dockedItems: [{
		               dock: 'top',
		               xtype: 'toolbar',
		               title: 'Bar Chart'
		           }],
		           stopMaskTapEvent: false,
		           fullscreen: false,
				   html: "This example's uses many interactions.<br><ul>" +
							"<li>A horizontal swipe will change between a grouped and stacked bar chart.</li>" +
							"<li>Tapping two items will overlay an arrow and show a comparison in the Title area.</li>" +
							"<li>The chart can be zoomed vertically with a pinch gesture, and the panned by dragging.  For devices which do not support multi-touch, an extra toggle button is made available to switch between pan and zoom.  When zoomed in, arrow indicators will be overlayed on the chart to show that more data is available</li>" +
							"<li>Double-Tap will reset the chart back to the initial state</li>"
		       }).show('pop');
		}


/***************************Area Chart***********************************************/
window.storeArea = new Ext.data.JsonStore({
            fields: mbfields,
            data: grphCur
        });


